package org.springblade.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.application.mapper.AppMapper;
import org.springblade.application.service.AppService;
import org.springblade.applicationapi.entity.App;
import org.springblade.applicationapi.entity.ApplicationManagementEntity;
import org.springblade.applicationapi.props.AppBuiltinProperties;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.entity.Dept;
import org.springblade.system.feign.ISysClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * description: AppServiceImpl <br>
 * date: 2022/4/6 11:42 <br>
 * author: yzpang <br>
 * version: 1.0 <br>
 */
@Service
@Slf4j
@AllArgsConstructor
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements AppService {
	private ISysClient sysClient;
	private AppBuiltinProperties appBuiltinProperties;

	@Override
	public Boolean addApp(App app) {
		this.save(app);
		return true;
	}

	@Override
	public App updateApp(App app) {
		int result = baseMapper.updateById(app);
		if (result == 0){
			log.error("应用{}更新失败", app.getAppName());
		}
		return baseMapper.selectById(app.getId());
	}

	@Override
	public App getAppByAppId(String appId) {
		App app = baseMapper.getAppByAppId(appId);
		return app;
	}

	@Override
	public App getAppByAppName(String appName) {
		App app = baseMapper.getAppByAppName(appName);
		return app;
	}

	@Override
	public List<App> getAppAll() {
		List<App> appList = baseMapper.findAppList();
		return appList;
	}

	@Override
	public List<App> findAppList() {
//1、查用户所在部门 及所有的父级部门 2、查所有的应用管理数据
		log.info("addressPage==>" + "current user = " + AuthUtil.getUser().toString());
		//查用户所在部门 及所有的父级部门
		Long deptId1 = Long.valueOf(AuthUtil.getDeptId());


		//递归查部门id
		R<List<Dept>> deptList = sysClient.getDeptList();
		String deptIdString = this.getDeptIdString(deptList,deptId1);
		String deptSubIdString = this.getSubIdString(deptList, deptId1);
		deptIdString= deptIdString + "," + deptSubIdString + ",";
		List<Long> deptIdlongList = Func.toLongList(deptIdString);

		Set<ApplicationManagementEntity> managementEntityList1 = new HashSet<>();
		for(Long longId : deptIdlongList){
			List<ApplicationManagementEntity> managementEntityList=baseMapper.getEntity(longId);
			managementEntityList1.addAll(managementEntityList);
		}

		List<Long> targetIdLong = managementEntityList1.stream().map(ApplicationManagementEntity::getTargetAddressId).collect(Collectors.toList());
		return baseMapper.selectAppPage(null, targetIdLong);
	}

	@Override
	public IPage<App> selectAppPage(IPage<App> page, App app, String order, String name){
		List<App> appList = baseMapper.selectQueryApp(page, app, order, name);
		return page.setRecords(appList);
	}

	@Override
	public IPage<App> selectAppPage(IPage<App> page) {
		//1、查用户所在部门 及所有的父级部门 2、查所有的应用管理数据
		log.info("addressPage==>" + "current user = " + AuthUtil.getUser().toString());
		//查用户所在部门 及所有的父级部门
		Long deptId1 = Long.valueOf(AuthUtil.getDeptId());


		//递归查部门id
		R<List<Dept>> deptList = sysClient.getDeptList();
		String deptIdString = this.getDeptIdString(deptList,deptId1);
		String deptSubIdString = this.getSubIdString(deptList, deptId1);
		deptIdString= deptIdString + "," + deptSubIdString + ",";
		List<Long> deptIdlongList = Func.toLongList(deptIdString);

		Set<ApplicationManagementEntity> managementEntityList1 = new HashSet<>();
		for(Long longId : deptIdlongList){
			List<ApplicationManagementEntity> managementEntityList=baseMapper.getEntity(longId);
			managementEntityList1.addAll(managementEntityList);
		}

		List<Long> targetIdLong = managementEntityList1.stream().map(ApplicationManagementEntity::getTargetAddressId).collect(Collectors.toList());
		return page.setRecords(baseMapper.selectAppPage(page, targetIdLong));
	}



	private String getDeptIdString(R<List<Dept>> deptList , Long deptId1) {
		String result = String.valueOf(deptId1);
		List<Dept> collect = deptList.getData().stream().filter(dept -> dept.getId().equals(deptId1)).collect(Collectors.toList());
		if (collect != null && collect.size() > 0) {
			Long parentId1 = collect.get(0).getParentId();
			if (!parentId1.equals(0L)) {
				result +=  "," + getDeptIdString(deptList, parentId1);
			}
		}
		return result;
	}
	// 获取下级部门id
	private String getSubIdString(R<List<Dept>> deptList , Long deptId1){
		String result = String.valueOf(deptId1);
		List<Dept> collect = deptList.getData().stream().filter(dept -> dept.getParentId().equals(deptId1)).collect(Collectors.toList());
		if (collect != null && collect.size() > 0) {
			// 深度搜索
			for (Dept dept: collect){
				result += "," + getSubIdString(deptList, dept.getId());
			}
		}
		return result;
	}

	@Override
	public Boolean deleteById(String ids) {
		String[] idList = ids.split(",");
		log.info("delete app {} ", ids);
		for (String id: idList) {
			baseMapper.deleteById(Long.valueOf(id));
		}
		return true;
	}

	@Override
	public boolean update(Wrapper<App> updateWrapper) {
		return super.update(updateWrapper);
	}

	/**
	 * 服务启动时更新内置应用配置
	 * */
	@Override
	public Boolean updateBuiltinApp() {
		List<App> appList = appBuiltinProperties.getApp();
		if (appList != null) {
			appList.stream().forEach((app) -> {
				if (StringUtil.isNotBlank(app.getAlias())) {
					log.info("启动时更新内置应用配置: " + app.getAlias());
					app.setUpdateTime(new Timestamp(System.currentTimeMillis()));
					baseMapper.updateByAlias(app);
				}
			});
		}
		return true;
	}
}
